/*
 * Copyright (C) 2009-2011 Geometer Plus <contact@geometerplus.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package com.esp.soccertutor.android.fbreader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.esp.soccertutor.R;
import com.esp.soccertutor.fbreader.bookmodel.TOCTree;
import com.esp.soccertutor.fbreader.fbreader.FBReaderApp;
import com.esp.soccertutor.uc.Table_Content_BottomMenu;
import com.esp.soccertutor.util.Const;
import com.esp.soccertutor.zlibrary.core.application.ZLApplication;
import com.esp.soccertutor.zlibrary.core.resources.ZLResource;
import com.esp.soccertutor.zlibrary.core.tree.ZLTree;
import com.esp.soccertutor.zlibrary.text.view.ZLTextWordCursor;

public class TOCActivity extends Activity {
	private TOCAdapter myAdapter;
	private ZLTree<?> mySelectedItem;
	private ListView _lv_toclistview;
	private Table_Content_BottomMenu tocmenu;
	private Button btnread;
	private TextView txtTableOfContent;
	public static boolean flag;
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		Thread.setDefaultUncaughtExceptionHandler(new com.esp.soccertutor.zlibrary.ui.android.library.UncaughtExceptionHandler(this));

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.toc_list);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		txtTableOfContent = (TextView) findViewById(R.id.txtTableOfContent);
		txtTableOfContent.setTypeface(Const.tf);
		
		_lv_toclistview=(ListView)findViewById(R.id._lv_toclistview);
		this.tocmenu=new Table_Content_BottomMenu(this,getLayoutInflater());
		
		flag = false;
		
		final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();
		final TOCTree root = fbreader.Model.TOCTree;
		myAdapter = new TOCAdapter(root);
		final ZLTextWordCursor cursor = fbreader.BookTextView.getStartCursor();
		int index = cursor.getParagraphIndex();	
		if (cursor.isEndOfParagraph()) {
			++index;
		}
		TOCTree treeToSelect = null;
		// TODO: process multi-model texts
		for (TOCTree tree : root) {
			final TOCTree.Reference reference = tree.getReference();
			if (reference == null) {
				continue;
			}
			if (reference.ParagraphIndex > index) {
				break;
			}
			treeToSelect = tree;
		}
		myAdapter.selectItem(treeToSelect);
		mySelectedItem = treeToSelect;
		_lv_toclistview.setAdapter(myAdapter);
		
		btnread=(Button)findViewById(R.id.btnRead);
		btnread.setOnClickListener(new OnClickListener() {
			
			
			public void onClick(View v) {
				
				startActivity(new Intent(TOCActivity.this, FBReader.class));
			}
		});
		
	}

	private static final int PROCESS_TREE_ITEM_ID = 0;
	private static final int READ_BOOK_ITEM_ID = 1;

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final int position = ((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position;
		final TOCTree tree = (TOCTree)myAdapter.getItem(position);
		switch (item.getItemId()) {
			case PROCESS_TREE_ITEM_ID:
				myAdapter.runTreeItem(tree);
				return true;
			case READ_BOOK_ITEM_ID:
				myAdapter.openBookText(tree);
				return true;
		}
		return super.onContextItemSelected(item);
	}

	private final class TOCAdapter extends ZLTreeAdapter {
		TOCAdapter(TOCTree root) {
			super(_lv_toclistview, root);
		}

		@Override
		public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
			final int position = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
			final TOCTree tree = (TOCTree)getItem(position);
			if (tree.hasChildren()) {
				menu.setHeaderTitle(tree.getText());
				final ZLResource resource = ZLResource.resource("tocView");
				menu.add(0, PROCESS_TREE_ITEM_ID, 0, resource.getResource(isOpen(tree) ? "collapseTree" : "expandTree").getValue());
				menu.add(0, READ_BOOK_ITEM_ID, 0, resource.getResource("readText").getValue());
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final View view = (convertView != null) ? convertView :
				LayoutInflater.from(parent.getContext()).inflate(R.layout.toc_tree_item, parent, false);
			final TOCTree tree = (TOCTree)getItem(position);
			view.setBackgroundColor((tree == mySelectedItem) ? 0xff808080 : 0);
			setIcon((ImageView)view.findViewById(R.id.toc_tree_item_icon), tree);
			((TextView)view.findViewById(R.id.toc_tree_item_text)).setText(tree.getText());
			return view;
		}

		void openBookText(TOCTree tree) {
			final TOCTree.Reference reference = tree.getReference();
			if (reference != null) {
				finish();
				final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();
				fbreader.addInvisibleBookmark();
				fbreader.BookTextView.gotoPosition(reference.ParagraphIndex, 0, 0);
				fbreader.showBookTextView();
			}
		}

		@Override
		protected boolean runTreeItem(ZLTree<?> tree) {
			if (super.runTreeItem(tree)) {
				return true;
			}
			openBookText((TOCTree)tree);
			return true;
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(flag){
			finish();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    if (keyCode == KeyEvent.KEYCODE_MENU) {
	    	System.out.println("PRESSED MENU BUTTON");
	    	doMenu();
	    	return true; //always eat it!	    	
	    }
	    else if(keyCode == KeyEvent.KEYCODE_BACK)
	    {
	    	if (tocmenu.isShowing()) {
	    		tocmenu.hide();
				return true;
	    	}
	    }
		return super.onKeyDown(keyCode, event); 
	} 
	private void doMenu() {
		if (tocmenu.isShowing()) {
			tocmenu.hide();
		} else {
			//Note it doesn't matter what widget you send the menu as long as it gets view.
			tocmenu.show(findViewById(R.id._rl_toctop));
		}
	}
}
